import React, { useEffect, /* useRef, */ useState } from 'react'

function useMousePosition(domSelector) {
    const [x, setX] = useState(0)
    const [y, setY] = useState(0)

    useEffect(
        () => {
            console.log("useMousePosition: ComponentDidMount");

            function onMouseMove(e) {
                console.log("onMouseMove", e);
                setX(e.pageX)
                setY(e.pageY)
            }

            document.querySelector(domSelector).addEventListener(
                "mousemove",
                onMouseMove
            )

            // 组件注销前 ComponentWillUnmount 注销事件
            return () => {
                console.log("useMousePosition: ComponentWillUnmount");
                document.querySelector(domSelector).removeEventListener(
                    "mousemove",
                    onMouseMove
                )
            }
        },
        []
    )

    return [x, y]
}

function App() {
    // const [x, setX] = useState(0)
    // const [y, setY] = useState(0)

    // useEffect(
    //     () => {
    //         console.log("ComponentDidMount");

    //         function onMouseMove(e) {
    //             console.log("onMouseMove", e);
    //             setX(e.pageX)
    //             setY(e.pageY)
    //         }

    //         document.body.addEventListener(
    //             "mousemove",
    //             onMouseMove
    //         )

    //         // 组件注销前ComponentWillUnmount注销事件
    //         return () => {
    //             document.body.removeEventListener(
    //                 "mousemove",
    //                 onMouseMove
    //             )
    //         }
    //     },

    //     []
    // )

    const [x, y] = useMousePosition("#root")

    return (
        <div style={{ height: "1000px", backgroundColor: "gray" }} id="root">
            当前鼠标位置: {x},{y}
            {console.log("App:rendered")}
        </div>
    )
}

export default App
